package admin.server.xxljob;

import admin.server.feign.FeishuJavaFeign;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import admin.common.constant.AuthConstant;
import admin.common.domain.rsp.EmployeeRsp;
import admin.common.domain.rsp.EmployeesRsp;
import admin.common.domain.rsp.R;
import admin.server.dao.UmsEmployeeDao;
import admin.server.exception.Asserts;
import admin.dao.model.UmsEmployee;

import java.util.ArrayList;
import java.util.List;


/**
 * @Description: TODO
 * @Author: zgb
 * @CreateDate: 2024/3/12 11:03
 */
@Slf4j
@Component
public class SyncEmployeeFromFeiShuJob {


    @Autowired
    private FeishuJavaFeign feishuJavaFeign;


    @Autowired
    private UmsEmployeeDao employeeDao;


    public UmsEmployee toEmployee(EmployeeRsp rsp) {
        UmsEmployee umsEmployee = new UmsEmployee();
        umsEmployee.setUserId(rsp.getUserId());
        umsEmployee.setEmployeeNo(rsp.getSystemFields().getEmployeeNo());
        umsEmployee.setEmployeeType(rsp.getSystemFields().getEmployeeType());
        umsEmployee.setEnName(rsp.getSystemFields().getEnName());
        umsEmployee.setName(rsp.getSystemFields().getName());
        umsEmployee.setStatus(rsp.getSystemFields().getStatus());
        return umsEmployee;
    }


    @XxlJob("syncEmployeeFromFeiShuJob")
    public void syncEmployeeFromFeiShuJob() {
        log.info("调用了>>>>>>>>>>>>>>>>>>>>>>>>>>>syncUserUsuallyMessage");
        syncEmployeeFromFeiShu();

    }

    public void syncEmployeeFromFeiShu() {
        List<EmployeeRsp> employeeRspList = new ArrayList<>();
        String tenantAccessToken = feishuJavaFeign.tenantAccessToken();
        employees(AuthConstant.JWT_TOKEN_PREFIX.concat(tenantAccessToken), null, employeeRspList);
        for (EmployeeRsp employeeRsp : employeeRspList) {
            employeeDao.insertOnDuplicate(toEmployee(employeeRsp));
        }
    }

    private void employees(String authorization, String pageToken, List<EmployeeRsp> employeeRspList) {
        R<EmployeesRsp> employeesRspR = feishuJavaFeign.employees(authorization, pageToken);
        if (employeesRspR == null) {
            Asserts.fail("调用 飞书 employees 接口异常:无返回");
        }
        if (employeesRspR.getCode() != 0) {
            Asserts.fail(String.format("调用 飞书 employees 接口异常:返回码 %s，异常信息 %s%s", employeesRspR.getCode(), employeesRspR.getMsg(), employeesRspR.getMessage()));
        }
        EmployeesRsp employeesRsp = employeesRspR.getData();
        List<EmployeeRsp> employeeRspList1 = employeesRsp.getItems();
        employeeRspList.addAll(employeeRspList1);
        Boolean hasMore = employeesRsp.getHasMore();
        while (hasMore) {
            employees(authorization, employeesRsp.getPageToken(), employeeRspList);
        }
    }


}
